#include "RenderCommand.h"
#include "PhnqletManager.h"
#include "Template.h"
#include <set>

namespace phnq
{
	namespace phnqlets
	{
		static set<string> getExts()
		{
			set<string> exts;
			exts.insert("html");
			exts.insert("js");
			exts.insert("css");
			return exts;
		}

		void RenderCommand::execute(string relPath, map<string,string> params, processor_response *response)
		{
			static set<string> exts = getExts();
		
			size_t lastDotIdx = relPath.find_last_of(".");
			string type = lastDotIdx == string::npos ? relPath : relPath.substr(0, lastDotIdx);
			string ext = lastDotIdx == string::npos ? "html" : relPath.substr(lastDotIdx+1);
		
			if(exts.find(ext) == exts.end())
			{
				ext = "html";
				type = relPath;
			}
			
			if(ext == "js" || ext == "css")
				response->clientCacheDuration = 60 * 60 * 24 * 365; // one year
				
			Phnqlet *phnqlet = PhnqletManager::getInstance()->get(type);
			if(phnqlet)
			{
				Template *mainTmplt = phnqlet->getTemplate("main");
				if(mainTmplt)
				{
					string resp = "";
					
					if(ext == "html")
						resp = mainTmplt->process();
					else if(ext == "js")
						resp = mainTmplt->processScript();
					else if(ext == "css")
						resp = mainTmplt->processStyle();

					response->bodyStream = new istringstream(resp);
				}
				else
				{
					response->status = STATUS_NOT_FOUND;
				}
			}
			else
			{
				response->status = STATUS_NOT_FOUND;
			}
		}
	}
}
